package hang.study.uistudy;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.lang.ref.WeakReference;

public class MainActivity extends Activity implements View.OnClickListener {

    public static final String ACTION_TIME_UPDATE = "hang.study.uistudy.ActionTimeUpdate";
    public static final String ACTION_TIMER_FINISHED = "hang.study.uistudy.ActionTimerFinished";
    private static final String TAG = "TimeTrackerActivity";
    public static int TIME_NOTIFICATION = 0;
    private long mStart = 0;
    private long mTime = 0;
    private TimeHandler mHandler;
    private TimeListAdapter mTimeListAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(Util.LogTag,"进入onCreate方法");
        mHandler = new TimeHandler(this);
        //
        TextView tvCounter = (TextView)findViewById(R.id.counter);
        tvCounter.setText(DateUtils.formatElapsedTime(0));

        Button btnStart = (Button)findViewById(R.id.start_stop);
        btnStart.setOnClickListener(this);
        Button btnReset = (Button)findViewById(R.id.reset);
        btnReset.setOnClickListener(this);

        if(mTimeListAdapter == null){
            mTimeListAdapter = new TimeListAdapter(this,0);
        }
        ((ListView)findViewById(R.id.time_list)).setAdapter(mTimeListAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy(){

        super.onDestroy();
    }

    private void startTimer(){
        mStart = System.currentTimeMillis();
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessage(0);

    }

    private void stopTime(){
        mHandler.removeMessages(0);
    }

    private boolean isTimerRunning(){
        return mHandler.hasMessages(0);
    }

    private void resetTimer(){
        stopTime();
        if(mTimeListAdapter != null){
            mTimeListAdapter.add(mTime/1000);
        }
        mTime = 0;
    }

    @Override
    public void onClick(View v) {
        Log.d(Util.LogTag,"enter onClick "+v.getId());
        Button btn = (Button)findViewById(R.id.start_stop);
        if(v.getId() == R.id.start_stop){
            //Log.d(logTag,"enter onClick ");

            if(isTimerRunning()){//停止
                stopTime();
                btn.setText(R.string.start);
                Util.ShowMsg(this,Long.toString(mTime));
            }else{
                startTimer();
                btn.setText(R.string.stop);
            }
        }else if(v.getId() == R.id.reset){
            resetTimer();

            ((TextView)findViewById(R.id.counter)).setText(DateUtils.formatElapsedTime(0));
            btn.setText(R.string.start);
        }

    }

    private void showNotify(){
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Context context = getApplicationContext();
        //CharSequence message = "Hello World";
        Intent intent = new Intent(this,MainActivity.class);
        String title = "Hello World";
        String message = "This is a message.";
        PendingIntent pendingintent = PendingIntent.getActivity(this,0,intent,0);
        //noti
    }

    private class TimeHandler extends Handler{
        private WeakReference<MainActivity> mActivityRef;

        public TimeHandler(MainActivity activity){
            mActivityRef = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg){
            //Log.d(Util.LogTag,"进入handleMessage");
            MainActivity activity = mActivityRef.get();
            if(activity != null) {
                //Log.d(Util.LogTag,"开始处理handleMessage");
                long current = System.currentTimeMillis();
                activity.mTime += current-activity.mStart;
                activity.mStart = current;
                //Log.d(Util.LogTag,String.valueOf(mTime));
                TextView counter = (TextView)activity.findViewById(R.id.counter);
                counter.setText(DateUtils.formatElapsedTime(activity.mTime/1000));

                sendEmptyMessageDelayed(0, 250);
            }
        }

    }
}
